package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/*
 *@AUTHOR:LIUCHAO;
 *@DATE: 2020/9/18 19:38
 */
@RequestMapping("/user")
@RestController
public class UserController {
    /*写个添加用户的方法,使用Bcrypt加密,从而使我们调用数据库*/
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;/*passwordEncoder.encode()使用bcrypt提供的方法对密码进行加密*/
    @Reference
    private UserService userService;


    @RequestMapping("/add")
    public void add(String username,String password){

        System.out.println(username+password);
        userService.addUser(username, passwordEncoder.encode(password));
    }
    //获取当前登录用户的用户名
    @RequestMapping("/getUsername")
    public Result getUsername()throws Exception{
        try{
            org.springframework.security.core.userdetails.User user =
                    (org.springframework.security.core.userdetails.User)
                            SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            System.out.println(user.getUsername());
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,user.getUsername());
        }catch (Exception e){
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }
    }

}
